package com.example.moshudriver.tools;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;

import com.BeeFramework.model.BeeQuery;
import com.BeeFramework.model.BusinessResponse;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.sgr.dykdriver.R;
import com.example.moshudriver.model.UserBalanceModel;
import com.example.moshudriver.protocol.ApiInterface;
import com.example.moshudriver.protocol.location_chargeResponse;
import com.external.androidquery.callback.AjaxStatus;

public class LocationManager implements AMapLocationListener, BusinessResponse {
	public LocationManagerProxy mLocationManagerProxy;
	private static LocationManager Instance;
	private static double latitude = 0; // 经度
	private static double longitude = 0; // 纬度
	private static String locaName; // 注册地址

	public static SharedPreferences shared, shared1;
	public static SharedPreferences.Editor editor, editor1;
	public static Context context;
	private static String locationName; // 地点名
	private static String locationDistrict; // 区 或者县名
	UserBalanceModel charge;

	public LocationManager(Context context) {
		LocationManager.context = context;
		shared = context.getSharedPreferences(O2OMobileAppConst.USERINFO, 0);
		shared1 = context.getSharedPreferences(
				O2OMobileAppConst.LOCATION_CHARGE, 0);// 位置计费表
		editor = shared.edit();
		editor1 = shared1.edit();
		charge = new UserBalanceModel(context);
		charge.addResponseListener(this);
		// Toast.makeText(context, "location", 2000).show();
		latitude = shared.getFloat("latitude", 0.0f);
		longitude = shared.getFloat("longitude", 0.0f);

		Instance = this;

		// 初始化定位，只采用网络定位
		mLocationManagerProxy = LocationManagerProxy.getInstance(context);
		// mLocationManagerProxy.setGpsEnable(false);
		// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
		// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用removeUpdates()方法来取消定位请求
		// 在定位结束后，在合适的生命周期调用destroy()方法
		// 其中如果间隔时间为-1，则定位只定一次,
		// 在单次定位情况下，定位无论成功与否，都无需调用removeUpdates()方法移除请求，定位sdk内部会移除
		if (2== BeeQuery.environment())//如果是开发环境那么就不实事定位了
		{
			mLocationManagerProxy.requestLocationData(
					LocationProviderProxy.AMapNetwork, -1, 10, this);
		}else{
			mLocationManagerProxy.requestLocationData(
					LocationProviderProxy.AMapNetwork, 5 * 1000, 10, this);
		}
		
		// if (2== BeeQuery.environment())//如果是开发环境那么就不实事定位了
		// {
		// mLocationManagerProxy.requestLocationData(
		// LocationProviderProxy.AMapNetwork, -1, 10, this);
		// }else{
		// mLocationManagerProxy.requestLocationData(
		// LocationProviderProxy.AMapNetwork, 5 * 1000, 10, this);
		// }

	}

	public static LocationManager getInstance() {
		return Instance;
	}

	public void refreshLocation() {
		mLocationManagerProxy = LocationManagerProxy.getInstance(context);
		// LocationManagerProxy.NETWORK_PROVIDER，代表使用手机网络定位；LocationProviderProxy.AMapNetwork，代表高德网络定位服务，混合定位。
		// mLocationManagerProxy.setGpsEnable(false);
		// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
		// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用removeUpdates()方法来取消定位请求
		// 在定位结束后，在合适的生命周期调用destroy()方法
		// 其中如果间隔时间为-1，则定位只定一次,
		// 在单次定位情况下，定位无论成功与否，都无需调用removeUpdates()方法移除请求，定位sdk内部会移除
		mLocationManagerProxy.requestLocationData(
				LocationProviderProxy.AMapNetwork, 6 * 1000, 10, this);
	}

	public void stopLocation() {
		if (mLocationManagerProxy != null) {
			mLocationManagerProxy.removeUpdates(this);
			mLocationManagerProxy.destory();
		}
		mLocationManagerProxy = null;
	}



	public static final double EARTH_RADIUS = 6378137.0;

	public static double gps2m(double lat_a, double lng_a, double lat_b,
			double lng_b) {
		double radLat1 = (lat_a * Math.PI / 180.0);
		double radLat2 = (lat_b * Math.PI / 180.0);
		double a = radLat1 - radLat2;
		double b = (lng_a - lng_b) * Math.PI / 180.0;
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
				+ Math.cos(radLat1) * Math.cos(radLat2)
				* Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return s;
	}

	public static double getLatitude() {
		shared = context.getSharedPreferences(O2OMobileAppConst.USERINFO, 0);
		editor = shared.edit();
		latitude = shared.getFloat("latitude", 0.0f);
		return latitude;
	}

	public static double getLongitude() {
		shared = context.getSharedPreferences(O2OMobileAppConst.USERINFO, 0);
		editor = shared.edit();
		longitude = shared.getFloat("longitude", 0.0f);
		return longitude;
	}

	public static String getLocaname() {
		shared = context.getSharedPreferences(O2OMobileAppConst.USERINFO, 0);
		editor = shared.edit();
		locaName = shared.getString("locaname", " ");
		return locaName;
	}

	@Override
	public void onLocationChanged(Location arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationChanged(AMapLocation arg0) {

		latitude = arg0.getLatitude();
		longitude = arg0.getLongitude();
		locaName = arg0.getProvince() + arg0.getCity();
		if (arg0.getCity().toString() != null) {
			if (arg0.getDistrict() != null) {
				charge.getLoccation_Charge(arg0.getDistrict().toString());
			} else {
				charge.getLoccation_Charge(arg0.getCity().toString());
			}

		}

		if (latitude > 1 && longitude > 1) {
			editor.putFloat("latitude", (float) latitude);
			editor.putFloat("longitude", (float) longitude);
			editor.putString("locaname", locaName);
			editor.commit();

			charge.RefreshLocation();
			// Toast.makeText(context, "定位成功", 2000).show();
		} else {

		}

	}

	public static String getLocation(double lat, double lon) {
		String loc = null;
		double s = gps2m(getLatitude(), getLongitude(), lat, lon);
		if (s > 1000) {
			s = s / 1000.0;
			s = Math.ceil(s * 100 + .5) / 100;
			loc = s + context.getString(R.string.kilometre);
		} else {
			s = Math.ceil(s * 100 + .5) / 100;
			loc = s + context.getString(R.string.meter);
		}
		return loc;

	}

	@Override
	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
			throws JSONException {
		if (url.endsWith(ApiInterface.USER_LOCATION_CHARGE)) {// 获取城市收费表成功
			location_chargeResponse response = new location_chargeResponse();
			response.fromJson(jo);

			editor1.putFloat("start_distant",
					response.charge.get(0).start_distant);
			editor1.putFloat("per_distant", response.charge.get(0).per_distant);
			editor1.putFloat("start_price", response.charge.get(0).start_price);
			editor1.putInt("isopen", response.charge.get(0).isopen);
			editor1.putString("lowest", response.charge.get(0).lowest);
			editor1.commit();

		} else if (url.endsWith(ApiInterface.LOCATION_REFRESH)) {
			// Toast.makeText(context, "更新位置", 2000).show();
		
		}

	}

}
